<template>
        <div class="container">
            <div class="form">
                <div class="saveBtn">
                    <div class="fixed">
                        <el-button type="primary" class="btn" @click="saveAction(formRef)">保存</el-button>
                        <el-button type="primary" plain class="btn" @click="cancelAction">返回</el-button>
                    </div>
                </div>
                <el-form :model="formData" ref="formRef" label-width="120px" :rules="rules" class="elForm">
                    <el-form-item label="环境名称" prop="envName">
                        <el-input 
                            v-model="formData.envName" 
                            placeholder="请输入环境名称"
                            :prefix-icon="EditPen"
                            class="inputClass"
                        />
                    </el-form-item>
                    <el-form-item label="环境分组" prop="groupID">
                        <el-select v-model="formData.groupID" class="m-2" placeholder="请选择分组">
                            <el-option
                                v-for="item in groups"
                                :key="item.groupID"
                                :label="item.groupName"
                                :value="item.groupID"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="标签" prop="tagIds">
                        <el-tag
                            v-for="tag in tagIds"
                            :key="tag"
                            class="mx-1 selectedTag"
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag)"
                        >
                            {{ getTagName(tag) }}
                        </el-tag>
                        <el-select 
                            v-if="inputVisible"
                            ref="InputRef"
                            v-model="inputValue" 
                            class="m-2" 
                            placeholder="请选择标签"
                            @change="handleInputConfirm"
                        >
                            <el-option
                                v-for="item in tagIdOptios"
                                :key="item.tagID"
                                :label="item.tagName"
                                :value="item.tagID"
                            />
                        </el-select>
                        <el-button v-else class="button-new-tag ml-1"  @click="showInput" size="small">
                            + 新建标签
                        </el-button>
                    </el-form-item>
                    <el-form-item label="设备名称" prop="deviceName">
                        <el-input 
                            v-model="formData.deviceName" 
                            placeholder="设备名称,如:DESKTOP-XRPA"
                            class="inputClass"
                        />
                        <el-button type="primary" plain @click="formData.deviceName=genDeviceName()" class="randomBtn">随机生成</el-button>
                    </el-form-item>
                    <el-form-item label="URL">
                        <el-input 
                            v-model="formData.url" 
                            placeholder="请输入URL"
                            type="textarea"
                            :prefix-icon="Link"
                            class="inputClass"
                        />
                    </el-form-item>
                    <el-form-item label="浏览器">
                        <el-radio-group v-model="formData.browser" class="ml-4">
                            <el-radio label="Chrome">Chrome</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="浏览器版本">
                        <el-select 
                            v-model="formData.browserVersion" 
                            class="m-2" 
                            placeholder="请选择浏览器版本"
                        >
                            <el-option
                                v-for="item in ['随机','108.0.5359','107.0.5304','106.0.5249','105.0.5195','104.0.5112','103.0.5060','102.0.5005','101.0.4951','100.0.4896','99.0.4844','98.0.4758','97.0.4692','96.0.4664','95.0.4638','94.0.4606','993.0.45773','92.0.4515','91.0.4472','90.0.4430','89.0.4389','88.0.4324']"
                                :key="item"
                                :label="item"
                                :value="item"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="操作系统" prop="os">
                        <el-select v-model="formData.os" placeholder="选择操作系统">
                            <el-option-group
                            v-for="group in OSOptions"
                            :key="group.label"
                            :label="group.label"
                            >
                            <el-option
                                v-for="item in group.options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                            </el-option-group>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="分辨率">
                        <el-select v-model="formData.resolution" placeholder="分辨率">
                            <el-option
                                v-for="item in resolutionOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    
                    <el-form-item label="Cookies" prop="cookie">
                        <el-input 
                            v-model="formData.cookie" 
                            placeholder="JSON格式"
                            type="textarea"
                            :prefix-icon="Notebook"
                            class="inputClass"
                        />
                    </el-form-item>
                    <el-form-item label="备注" prop="mark">
                        <el-input 
                            v-model="formData.mark" 
                            placeholder="备注信息"
                            type="textarea"
                            :prefix-icon="Notebook"
                            class="inputClass"
                        />
                    </el-form-item>
                    <el-form-item label="排序" prop="mOrder">
                        <el-input 
                            v-model="formData.mOrder" 
                            placeholder="请输入排序, 数值越大越靠前"
                            :prefix-icon="Sort"
                            class="inputClass"
                        />
                    </el-form-item>

                    <el-form-item label="User Agent" prop="userAgent">
                        <el-input 
                            v-model="formData.userAgent" 
                            placeholder=""
                            class="inputClass"
                        />
                        <el-button type="primary" plain @click="genUserAgent" class="randomBtn">随机生成</el-button>
                    </el-form-item>
                    <el-form-item label="时区" prop="timeZone">
                        <el-select v-model="formData.timeZone" filterable placeholder="选择时区">
                            <el-option
                            v-for="item in timeZones"
                            :key="item.TimeZone"
                            :label="item.TimeZone"
                            :value="item.TimeZone"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="WebRTC" prop="webRTC">
                        <el-radio-group v-model="formData.webRTC">
                            <el-radio-button label="开启" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="地理位置" prop="location">
                        <el-radio-group v-model="formData.location">
                            <el-radio-button label="开启" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="语言" prop="language">
                        <el-input 
                            v-model="formData.language" 
                            placeholder="zh-CN,en..."
                            class="inputClass"
                        />
                    </el-form-item>
                    <el-form-item label="硬件加速" prop="acceleration">
                        <el-radio-group v-model="formData.acceleration">
                            <el-radio-button label="开启" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="Canvas" prop="canvas">
                        <el-radio-group v-model="formData.canvas">
                            <el-radio-button label="混淆" />
                            <el-radio-button label="默认" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="WebGL" prop="webgl">
                        <el-radio-group v-model="formData.webgl">
                            <el-radio-button label="混淆" />
                            <el-radio-button label="默认" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="WebGL元数据" prop="canvas">
                        <div class="webglmeta">
                            <el-radio-group v-model="formData.webglMetaEnable">
                                <el-radio-button label="自定义" />
                                <el-radio-button label="默认" />
                            </el-radio-group>
                            <el-form-item class="webglInput" label="预设" v-if="formData.webglMetaEnable == '自定义'">
                                <el-select 
                                    v-model="formData.webGLCorp" 
                                    class="m-2" 
                                    placeholder="预设元数据"
                                    @change="formData.webGLRender=randomWebglRenderer(formData.webGLCorp)"
                                >
                                    <el-option
                                        v-for="item in webglOptions"
                                        :key="item.label"
                                        :label="item.label"
                                        :value="item.label"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item class="webglInput" label="WebGL厂商" prop="webGLCorp"  v-if="formData.webglMetaEnable == '自定义'">
                                <el-input 
                                    v-model="formData.webGLCorp" 
                                    placeholder="如: Google Inc."
                                    class="inputClass"
                                />
                            </el-form-item>
                            <el-form-item class="webglInput" label="WebGL渲染" prop="webGLRender"  v-if="formData.webglMetaEnable == '自定义'">
                                <el-input 
                                    v-if="formData.webglMetaEnable == '自定义'"
                                    v-model="formData.webGLRender" 
                                    placeholder="如: ANGLE (Intel, Intel(R) UHD Graphics 620 Direct3D11 vs_5_0 ps_5_0, D3D11-27.20.100.8190)"
                                    class="inputClass"
                                />
                                <el-button type="primary" plain @click="formData.webGLRender=randomWebglRenderer(formData.webGLCorp)" class="randomBtn">随机</el-button>
                            </el-form-item>
                            
                        </div>
                        
                    </el-form-item>
                    <el-form-item label="Mac" prop="mac">
                    <div class="macaddress">
                        <el-radio-group v-model="formData.macEnable">
                            <el-radio-button label="自定义" />
                            <el-radio-button label="默认" />
                        </el-radio-group>
                        <el-form-item class="macInput" v-if="formData.macEnable == '自定义'">
                        <el-input 
                            v-model="formData.mac" 
                            placeholder="如: aa-aa-aa-aa-aa-aa"
                            class="inputClass macInputClass"
                        />
                            <el-button v-if="formData.macEnable == '自定义'" type="primary" plain @click="formData.mac=genMac()" class="randomBtn">随机</el-button>
                        </el-form-item>
                    </div>
                    </el-form-item>
                    <el-form-item label="反跟踪" prop="doNotTrack">
                        <el-radio-group v-model="formData.doNotTrack">
                            <el-radio-button label="开启" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="AudioContext" prop="audioContext">
                        <el-radio-group v-model="formData.audioContext">
                            <el-radio-button label="混淆" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="媒体设备" prop="mediaDevice">
                        <el-radio-group v-model="formData.mediaDevice">
                            <el-radio-button label="混淆" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="SpeechVoice" prop="speechVoice">
                        <el-radio-group v-model="formData.speechVoice">
                            <el-radio-button label="混淆" />
                            <el-radio-button label="关闭" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="硬件并发数">
                        <el-select 
                            v-model="formData.concurrent" 
                            class="m-2" 
                            placeholder="请选择硬件并发数"
                        >
                            <el-option
                                v-for="item in ['系统默认','2','4','6','8','10','12','14','16','18','20','22','24']"
                                :key="item"
                                :label="item"
                                :value="item"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="内存">
                        <el-select 
                            v-model="formData.mem" 
                            class="m-2" 
                            placeholder="请选择内存容量"
                        >
                            <el-option
                                v-for="item in ['系统默认','2','4','6','8','10','12','14','16','18','20','22','24']"
                                :key="item"
                                :label="item"
                                :value="item"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div class="right">
                <Info v-model:data="formData"></Info>
            </div>
            
        </div>
        
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed, defineProps, defineEmits, watch, nextTick, render} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import { ElMessage, ElMessageBox, ElInput} from 'element-plus'
import Info from './Info.vue';
import type { FormInstance, FormRules } from 'element-plus'
import { Sort, EditPen, Notebook, Link} from '@element-plus/icons-vue'
import EnvApi from '../../../apis/env'
import {useUserStore} from '../../../stores/user'
import { FormValid } from '../../../utils/FormUtils'
import {genEnvInfo} from './Utils/EnvGenerator'
import timeZone from './Utils/timezone.json'
import { rand } from '@vueuse/shared';
import { random } from 'lodash';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore()

const timeZones = timeZone.TimeZones.List;
const groups = ref<Array<{groupID:string,groupName:string}>>([])
const inputValue = ref('')
const tagIds = ref<Array<string>>([]);
const tagIdOptios = ref<Array<{tagID:string, tagName:string}>>([]);
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const props = defineProps({

})

const formRef = ref<FormInstance>()
const formData = ref({
    envName:"",
    groupID: "",
    mOrder: 0,
    mark:"",
    url: "",
    browser: "Chrome",
    browserVersion: "108.0.5359",
    os:"",
    cookie: "",
    userAgent:"",
    timeZone:"Asia/Shanghai",
    webRTC: "开启",
    location: "开启",
    language: "zh-CN",
    acceleration: "开启",
    canvas: "默认",
    webgl: "默认",
    webGLCorp: "Google Inc.",
    webGLRender: "ANGLE (Intel, Intel(R) UHD Graphics 620 Direct3D11 vs_5_0 ps_5_0, D3D11-27.20.100.8190)",
    deviceName: "DESKTOP-SKMVUM",
    resolution: "默认",
    macEnable: "默认",
    mac:"",
    webglMetaEnable: "默认",
    doNotTrack: "开启",
    audioContext: "混淆",
    mediaDevice: "混淆",
    speechVoice: "混淆",
    concurrent: "系统默认",
    mem: "系统默认"
});
const OSOptions = [
  {
    label: 'Windows',
    options: [
        {
            value: 'random_Windows',
            label: '随机Windows',
        },{
            value: 'Windows11',
            label: 'Windows 11',
        },{
            value: 'Windows10',
            label: 'Windows 10',
        },{
            value: 'Windows9',
            label: 'Windows 9',
        },{
            value: 'Windows8',
            label: 'Windows 8',
        },{
            value: 'Windows7',
            label: 'Windows 7',
        }
    ],
  },
  {
    label: 'Mac',
    options: [
        {
            value: 'random_Mac',
            label: '随机Mac',
        },{
            value: 'MacVentura',
            label: 'Mac Ventura',
        },{
            value: 'MacMonterey',
            label: 'Mac Monterey',
        },{
            value: 'MacBigSur',
            label: 'Mac Big Sur',
        },{
            value: 'MacMojave',
            label: 'Mac Mojave',
        },{
            value: 'MacHighSierra',
            label: 'Mac High Sierra',
        },{
            value: 'MacSierra',
            label: 'Mac Sierra',
        },
    ],
  },{
    label: 'Linux',
    options: [
        {
            value: 'random_Linux',
            label: '随机Linux',
        },{
            value: 'LinuxCentOS',
            label: 'Linux CentOS',
        },{
            value: 'LinuxUbuntu',
            label: 'Linux Ubuntu',
        },{
            value: 'LinuxDebian',
            label: 'Linux Debian',
        }
    ],
  },{
    label: 'Android',
    options: [
        {
            value: 'random_Android',
            label: '随机Android',
        },{
            value: 'Android11',
            label: 'Android 11',
        },{
            value: 'Android10',
            label: 'Android 10',
        },{
            value: 'Android9',
            label: 'Android 9',
        },{
            value: 'Android8',
            label: 'Android 8',
        }
    ],
  },{
    label: 'iOS',
    options: [
        {
            value: 'random_iOS',
            label: '随机iOS',
        },{
            value: 'iOS16.2',
            label: 'iOS 16.2',
        },{
            value: 'iOS15.7.2',
            label: 'iOS 15.7.2',
        },{
            value: 'iOS14.8.1',
            label: 'iOS 14.8.1',
        },{
            value: 'iOS13.7',
            label: 'iOS 13.7',
        }
    ],
  }
]

const resolutionOptions = [
    {
        value: '默认',
        label: '默认',
    },{
        value: '800*600',
        label: '800*600',
    },{
        value: '1024*600',
        label: '1024*600',
    },{
        value: '1280*800',
        label: '1280*800',
    },{
        value: '1920*1080',
        label: '1920*1080',
    },{
        value: '2560*1440',
        label: '2560*1440',
    }
]

const webglOptions = [
    {
        label: 'Google Inc.',
        value: [
            "ANGLE (Intel, Intel(R) HD Graphics Direct3D9Ex vs_3_0 ps_3_0, igdumd64.dll-9.17.10.4101)",
            "ANGLE (AMD Radeon HD 7900 Series Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (Intel(R) HD Graphics 4000 Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (Intel(R) HD Graphics 4600 Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (Intel(R) HD Graphics 520 Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (Intel(R) HD Graphics 530 Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (Intel(R) HD Graphics Family Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (NVIDIA GeForce GTX 960 Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (NVIDIA GeForce GTX 1070 Direct3D11 vs_5_0 ps_5_0)",
            "ANGLE (NVIDIA GeForce GTX 760 Direct3D11 vs_5_0 ps_5_0)"
        ],
    },
    {
        label: 'Apple Inc.',
        value: ['Apple GPU', 'Apple M1']
    },
    {
        label: 'Intel Inc.',
        value: ['Intel(R) Iris(TM) Graphics 6100']
    },
    {
        label: 'ARM',
        value: ['Mali-T880']
    },
]



const rules = reactive<FormRules>({
    envName: [
        { required: true, message: '请输入环境名称', trigger: 'blur' },
        { min: 3, max: 32, message: '最小长度3, 最大长度16', trigger: 'blur' },
    ],
    url: [
        { required: true, message: '请输入URL', trigger: 'blur' },
        { min: 3, max: 32, message: '最小长度3, 最大长度16', trigger: 'blur' },
    ],
    groudId: [
        { required: true, message: '请选择分组', trigger: 'change' },
    ],
    mOrder: [
        { required: true, message: '请输入排序, 数字', trigger: 'blur' },
    ],
    deviceName: [
        { required: true, message: '请输入设备名称', trigger: 'blur' },
        { min: 3, max: 32, message: '最小长度3, 最大长度16', trigger: 'blur' },
    ],
    os: [
        { required: true, message: '请选择操作系统', trigger: 'change' }
    ],
    userAgent:[
        { required: true, message: '请输入UserAgent', trigger: 'blur' },
        { min: 3, max: 128, message: '最小长度3, 最大长度128', trigger: 'blur' },
    ]
})

onMounted(()=>{
    loadData();
})

const loadData = ()=>{
    EnvApi.fetchEnvGroup("", 0, 999).then(ret=>{
        if(ret.code == 0){
            groups.value = ret.data.list;
        }
    }).catch(err=>{
        console.log("[CreateEnv]fetchEnvGroup err", err);
    })

    EnvApi.fetchEnvTag("", 0, 999).then(ret=>{
        if(ret.code == 0){
            tagIdOptios.value = ret.data.list;
        }
    }).catch(err=>{
        console.log("[CreateEnv]fetchEnvTag err", err);
    });
    genUserAgent();
    formData.value.deviceName = genDeviceName();
}

const getTagName = (tagId:string) =>{
    let filter = tagIdOptios.value.filter(item=>item.tagID == tagId);
    if(filter && filter.length>0){
        return filter[0].tagName;
    }
}

const handleClose = (tag: string) => {
  tagIds.value.splice(tagIds.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    tagIds.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const saveAction = (formRef: FormInstance | undefined)=>{
    if (!formRef) return;
    FormValid(formRef).then(ret=>{
        return EnvApi.createEnv({
            "envName": formData.value.envName,
            "url": formData.value.url,
            "groupID": formData.value.groupID,
            "tagIDs": tagIds.value,
            "browser": formData.value.browser,
            "browserVersion": formData.value.browserVersion,
            "os": formData.value.os,
            "cookie": formData.value.cookie,
            "mark": formData.value.mark,
            "userAgent": formData.value.userAgent,
            "timeZone": formData.value.timeZone,
            "webRTC": formData.value.webRTC,
            "location": formData.value.location,
            "language": formData.value.language,
            "acceleration": formData.value.acceleration,
            "canvas": formData.value.canvas,
            "deviceName": formData.value.deviceName,
            "resolution": formData.value.resolution,
            "mac": formData.value.mac,
            "macEnable": formData.value.macEnable,
            "webgl": formData.value.webgl,
            "webglMetaEnable": formData.value.webglMetaEnable,
            "webGLCorp": formData.value.webGLCorp,
            "webGLRender": formData.value.webGLRender,
            "doNotTrack": formData.value.doNotTrack,
            "audioContext": formData.value.audioContext,
            "mediaDevice": formData.value.mediaDevice,
            "speechVoice": formData.value.speechVoice,
            "concurrent": formData.value.concurrent,
            "mem": formData.value.mem,
            "mOrder": formData.value.mOrder

        });
    }).then(ret=>{
        if(ret.code == 0){
            ElMessage({
                type: 'success',
                message: "新建成功",
            });
            setTimeout(async () => {
                router.back();
            }, 1500);
        }else{
            ElMessage({
                type: 'error',
                message: "新建失败",
            });
        }
    }).catch(err=>{
        ElMessage({
            type: 'error',
            message: err
        });
    })
}

const cancelAction = () => {
    console.log('cancel Action');
    router.back();
}

const genUserAgent = () => {
    formData.value.userAgent =  genEnvInfo(formData.value).userAgent;
}

const genDeviceName = (len=6) => {
	var  orgStr='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let returnStr="";
	for (var i = 0; i < len; i++) {
		returnStr+=orgStr.charAt(Math.floor((Math.random()*orgStr.length)));
	}
	return "DESKTOP-"+returnStr
}

const randomWebglRenderer = (corp:any)=>{
    let filter = webglOptions.filter(item=>item.label == corp);
    if(filter && filter.length>0){
        let renderers = filter[0].value;
        if(renderers.length == 1){
            return renderers[0];
        }else{
            let maxNum:number = renderers.length-1;
            let minNum:number = 0;
            let randomNum = Math.floor(Math.random() * (maxNum - minNum) + minNum);
            return renderers[randomNum];
        }
    }
    return "";
}

const genMac = ()=>{
    return "XX:XX:XX:XX:XX:XX".replace(/X/g, function() {
        return "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))
    });
}
</script>

<style scoped>
.container{
    display: flex;
    flex-direction: row;
}
.form{
    width: 100%;
    background-color: white;
    border-radius: 5px;
    padding: 10px;
    position: relative;
}
.elForm {
    z-index: 99;
}
.right {
    width: 300px;
    margin-left: 10px;
    margin-right: 0px;
    background-color: white;
    border-radius: 5px;
}
.selectedTag {
    margin-top: 3px;
    margin-right: 5px;
    margin-bottom: 3px;
}
.inputClass{
    width: 215px;
}
.macInputClass{
    margin-left: 0px;
}
.webglmeta, .macaddress {
    display:flex; 
    flex-direction: column;
}

.webglInput, .macInput {
    margin-top: 5px;
}

.saveBtn {
    position: absolute;
    right: 10px;
    top: 5px;
    width: 100px;
    height: 100px;
    z-index: 100;
}
.fixed{
    position: fixed;
    display: flex;
    flex-direction: column;
    justify-content: end;
    align-items: end;
    width: 100px;
}
.fixed .btn{
    margin:0px;
    margin-top: 5px;
}

.randomBtn {
    margin-left: 5px;
}
</style>
